const fs = require('fs')
const {getExternals, linkPackages, buildPackage} = require('./util')
const {Builder, Runner} = require('nwjs-builder-phoenix')

module.exports = (api, options) => {
  options.module = Object.assign(options.module || {}, {exprContextCritical: false})

  options.target = 'node-webkit'

  const pluginOptions = options.pluginOptions && options.pluginOptions.nwBuilder ? options.pluginOptions.nwBuilder : {}
  const externals = getExternals(api, pluginOptions)
  api.service.webpackChainFns.push(config => config.set('externals', externals))

  api.registerCommand(
    'serve:nw',
    {
      description: 'run with nw.js',
      usage: 'vue-cli-service serve:nw [options]',
      options: {'--x86': 'for x86', '--x64': 'for x64', '--chrome-app': 'for chrome-app', '--detached': 'detached'}
    },
    async args => {
      await api.service.run('serve', {}, [])
      buildPackage(api, options, pluginOptions, `http://localhost:${options.devServer.port || '8080'}`)
      // TODO native module?
      //linkPackages(api, externals)
      await new Runner({
        x86: args.x86,
        x64: args.x64,
        chromeApp: args['chrome-app'],
        mirror: 'https://npm.taobao.org/mirrors/nwjs/',
        detached: args.detached,
        mute: false,
      }, [options.outputDir]).run();
    }
  )

  api.registerCommand(
    'build:nw',
    {
      description: 'build with nw.js',
      usage: 'vue-cli-service build:nw [options]',
      options: {
        '--win': 'for Windows', '--mac': 'for macOS', '--linux': 'for Linux',
        '--x86': 'for x86', '--x64': 'for x64', '--tasks': 'like: win-x86,win-x64,linux-x86,linux-x64,mac-x64',
        '--chrome-app': 'for chrome-app', '--concurrent': 'concurrent', '--forceCaches': 'forceCaches'
      }
    },
    async args => {
      await api.service.run('build', {}, [])
      buildPackage(api, options, pluginOptions, options.indexPath)
      // TODO native module?
      //linkPackages(api, externals)
      await new Builder({
        win: args.win,
        mac: args.mac,
        linux: args.linux,
        x86: args.x86,
        x64: args.x64,
        tasks: (args.tasks || 'win-x86').split(','),
        chromeApp: args['chrome-app'],
        mirror: 'https://npm.taobao.org/mirrors/nwjs/',
        concurrent: args.concurrent,
        forceCaches: args.forceCaches,
        destination: api.service.pkg.destination,
        mute: false,
      }, options.outputDir).build();
    }
  )
}

module.exports.defaultModes = {
  'nw:build': 'production',
  'build:nw': 'production',
  'serve:nw': 'development',
  'nw:serve': 'development'
}